<?php

namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Shoppingrule;
use think\Db;
use think\Cache;

class Shoppingdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'shopping_id';

    protected $name = 'shopping';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'is_default'
    ];

    public $param = array();

    public $last_id = 0;

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (!isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeMemberId($query, $member_id)
    {
        $query->where('member_id', $member_id);
    }

    public function scopeShoppingId($query, $shopping_id)
    {
        $query->where('shopping_id', $shopping_id);
    }

    protected function setIsDefaultAttr()
    {
        if (isset($this->param['is_default']) && $this->param['is_default'] == 'on') {
            return 1;
        } else {
            return 0;
        }
    }

    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['member_id']) && $this->param['member_id'] != '') {
            $query->memberId($this->param['member_id']);
        }
        if (isset($this->param['shopping_id']) && $this->param['shopping_id']) {
            $query->shoppingId($this->param['shopping_id']);
        }
        if (isset($this->param['is_default']) && $this->param['is_default']) {
            $query->isDefault($this->param['is_default']);
        }
    }

    public function scopeIsDefault($query, $is_default)
    {
        $query->where('is_default', $is_default);
    }

    public function ajaxFind($shopping_id = '')
    {
        if ($shopping_id) {
            $this->param['shopping_id'] = $shopping_id;
        }
        $data = $this->master()->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return '';
        }
    }

    public function ajaxApiFind()
    {
        $data = $this->master()
            ->cache(false)
            ->order('shoping_id desc')
            ->find();
        if ($data) {
            $data = $data->toArray();
            return $data;
        } else {
            return '';
        }
    }

    // 查询
    public function ajaxSelect()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $limit = isset($this->param['limit']) ? $this->param['limit'] : 10;
        $data = $this->order('is_default desc,shopping_id desc')
            ->group('street')
            ->page(1, $limit)
            ->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxCount()
    {
        $count = $this->cache($this->cache_name('shopping_count'), 86400, 'shopping')
            ->count();
        return $count;
    }

    public function setDefault()
    {
        $this->useGlobalScope(false)
            ->where('member_id', $this->param['member_id'])
            ->update([
                'is_default' => 0
            ]);
        $this->useGlobalScope(false)
            ->where('shopping_id', $this->param['shopping_id'])
            ->update([
                'is_default' => 1
            ]);
        Cache::clear('shopping');
        return 'success';
    }

    public function ajaxSave()
    {
        $rule = new Shoppingrule();
        Db::startTrans();
        if (isset($this->param['is_default']) && $this->param['is_default'] == 'on') {
            $this->useGlobalScope(false)
                ->where('member_id', $this->param['member_id'])
                ->update([
                    'is_default' => 0
                ]);
        }
        $save_data = $this->param;
        if(is_numeric($save_data['province'])){
            $save_data['province'] = Db::name('jun_city')->where('citycode',$save_data['province'])->value('cityname');
            $save_data['city'] = Db::name('jun_city')->where('citycode',$save_data['city'])->value('cityname');
            $save_data['area'] = Db::name('jun_city')->where('citycode',$save_data['area'])->value('cityname');
        }
        if (isset($this->param['shopping_id']) && $this->param['shopping_id'] != '') {
            if (!$rule->scene('edit')->check($this->param)) {
                Db::rollback();
                return $rule->getError();
            }
            $this->save($save_data, [
                'shopping_id' => $this->param['shopping_id']
            ]);
        } else {
            if (!$rule->check($this->param)) {
                Db::rollback();
                return $rule->getError();
            }
            $this->allowField(true)->save($save_data);
        }
        Db::commit();
        Cache::clear('shopping');
        $this->last_id = $this->data['shopping_id'];
        return 'success';
    }

    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['shopping_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('shopping_id', 'IN', $this->param['shopping_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('shopping_id', 'IN', $this->param['shopping_id']);
                }, true);
            }
            Cache::clear('shopping');
            return 'success';
        }
    }


    protected function handleData($val)
    {
        $json_str = file_get_contents('./static/js/jqcity/allcity.js');
        $json_str = str_replace('callback(', '', $json_str);
        $json_str = str_replace(');', '', $json_str);
        $json_arr = json_decode($json_str, true);
        $val['province_name'] = $val['province'];
        $val['city_name'] = $val['city'];
        $val['area_name'] = $val['area'];
        foreach ($val as $k => $v) {
            switch ($k) {
                case 'province':
                    if (!is_numeric($v)) {
                        foreach ($json_arr['province'] as $key1 => $val1) {
                            if ($val1['name'] == $v) {
                                $val['province'] = $val1['id'];
                            }
                        }
                        break;
                    }
                    for ($i = 0; $i < count($json_arr['province']); $i++) {
                        if ($v == $json_arr['province'][$i]['id']) {
                            $val['province_name'] = $json_arr['province'][$i]['name'];
                            break;
                        }
                    }
                    break;
                case 'city':
                    if (!is_numeric($v)) {
                        if (isset($json_arr['city'][$val['province']])) {
                            foreach ($json_arr['city'][$val['province']] as $key1 => $val1) {
                                if ($val1['name'] == $v) {
                                    $val['city'] = $val1['id'];
                                }
                            }
                        }
                        break;
                    }
                    if (isset($json_arr['city'][$val['province']])) {
                        for ($i = 0; $i < count($json_arr['city'][$val['province']]); $i++) {
                            if ($v == $json_arr['city'][$val['province']][$i]['id']) {
                                $val['city_name'] = $json_arr['city'][$val['province']][$i]['name'];
                                break;
                            }
                        }
                    } else {
                        $val['city_name'] = $val;
                    }
                    break;
                case 'area':
                    if (!is_numeric($v)) {
                        if (isset($json_arr['district'][$val['city']])) {
                            foreach ($json_arr['district'][$val['city']] as $key1 => $val1) {
                                if ($val1['name'] == $v) {
                                    $val['area'] = $val1['id'];
                                }
                            }
                        }

                        break;
                    }
                    if (isset($json_arr['district'][$val['city']])) {
                        for ($i = 0; $i < count($json_arr['district'][$val['city']]); $i++) {
                            if ($v == $json_arr['district'][$val['city']][$i]['id']) {
                                $val['area_name'] = $json_arr['district'][$val['city']][$i]['name'];
                                break;
                            }
                        }
                    } else {
                        $val['area_name'] = $val;
                    }
                    break;
            }
        }
        return $val;
    }
}